﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;

using Wicresoft.Framework.Organization;
using Wicresoft.Busi.BizLogic;
using Wicresoft.Busi.Entity;

public partial class Car_VehicleApplyInfo_Week : BaseAuthenticationPage
{
    #region VehicleGroups
    private DataTable VehicleGroups
    {
        get
        {
            if (ViewState["VehicleGroups"] != null)
                return (DataTable)ViewState["VehicleGroups"];
            else
                return null;
        }
        set
        {
            ViewState["VehicleGroups"] = value;
        }
    }
    #endregion

    #region bEdit
    private bool bEdit
    {
        get
        {
            if (ViewState["bEdit"] != null)
                return (bool)ViewState["bEdit"];
            else
                return false;
        }
        set
        {
            ViewState["bEdit"] = value;
        }
    }
    #endregion

    #region bSpecial
    private bool bSpecial
    {
        get
        {
            if (ViewState["bSpecial"] != null)
                return (bool)ViewState["bSpecial"];
            else
                return false;
        }
        set
        {
            ViewState["bSpecial"] = value;
        }
    }
    #endregion

    public DateTime ThisDay
    {
        get
        {
            if (this.ViewState["ThisDay"] == null)
            {
                this.ViewState["ThisDay"] = DateTime.Now;
            }
            return Convert.ToDateTime(this.ViewState["ThisDay"]);
        }
        set
        {
            this.ViewState["ThisDay"] = value;
        }
    }


    protected void Page_Load(object sender, System.EventArgs e)
    {
        //VehicleApplyWeekTable1.UserID = CurrentUser.ID;
        if (!Page.IsPostBack)
        {
            this.bEdit = OrganizationHelper.IsUserInRole(CurrentUser.ID, VehicleRoles.Apply);
            //this.bSpecial = IsInRole(VehicleRoles.Register);

            for (int i = DateTime.Today.Year - 3; i <= DateTime.Today.Year + 5; i++)
            {
                this.ddlYear.Items.Add(i.ToString());
            }
            this.ddlYear.SelectedIndex = 3;

            for (int i = 1; i <= 12; i++)
            {
                this.ddlMonth.Items.Add(i.ToString());
            }
            this.ddlMonth.SelectedIndex = DateTime.Today.Month - 1;

            //VehicleGroups = BLVehicleGroups.GetVehicleGroups(BasePage.GetDept(CurrentUser.ID).ID);
        }

        LoadData();
    }

    private void LoadData()
    {
        //获取当天所在周的第一天

        DateTime dtTemp;
        if (Request.Form["txtDate"] == null || Request.Form["txtDate"].ToString() == "")
        {
            dtTemp = DateTime.Today;
            while (!dtTemp.DayOfWeek.ToString().Equals("Monday"))
                dtTemp = dtTemp.AddDays(-1);
        }
        else
            dtTemp = DateTime.Parse(Request.Form["txtDate"].ToString());

        InitTable(dtTemp);
    }

    private void InitTable(DateTime dtTemp)
    {
        String StartTime = dtTemp.ToString("yyyy-MM-dd");
        //String EndTime = dtTemp.AddDays(7).ToString("yyyy-MM-dd");
        String EndTime = dtTemp.AddDays(5).ToString("yyyy-MM-dd");

        string[] strArray = new string[] { VehicleStatus.OPENED, VehicleStatus.CLOSED, VehicleStatus.SPECIAL };
        DataTable dtVehicles = BLVehicles.GetVehicles(strArray, this.CurrentUser.ID);
        string[] strArray2 = new string[] { VehicleUseStatus.AUDIT };
        DataTable dtApply = GetVehicleApply(strArray, strArray2, DateTime.Parse(StartTime), DateTime.Parse(EndTime), this.CurrentUser.ID);
        DrawMainTable(dtVehicles, dtApply, dtTemp);
        this.txtDate.Text = dtTemp.ToString("yyyy-MM-dd");
    }

    public static DataTable GetVehicleApply(string[] VehicleStatus, string[] UseStatus, DateTime dtStart, DateTime dtEnd, Guid UserID)
    {
        string str = "";
        Guid guid = BasePage.GetDept(UserID).ID;
        for (int i = 0; i < UseStatus.Length; i++)
        {
            if (!UseStatus[i].Equals(string.Empty))
            {
                str = str + ",'" + UseStatus[i] + "'";
            }
        }
        if (str.Length > 0)
        {
            str = str.Substring(1);
        }
        StringBuilder builder = new StringBuilder();
        builder.Append(" 1=1");
        if (!str.Equals(string.Empty))
        {
            builder.Append(" AND Status IN (" + str + ")");
        }
        if ((((dtStart != DateTime.MinValue) && (dtStart != DateTime.MaxValue)) && (dtEnd != DateTime.MinValue)) && (dtEnd != DateTime.MaxValue))
        {
            builder.Append(" AND (StartDate >= '" + dtStart.ToString("yyyy-MM-dd") + "' AND StartDate <= '" + dtEnd.ToString("yyyy-MM-dd") + "'");
            builder.Append(" OR EndDate >= '" + dtStart.ToString("yyyy-MM-dd") + "' AND EndDate <= '" + dtEnd.ToString("yyyy-MM-dd") + "'");
            builder.Append(" OR StartDate <= '" + dtStart.ToString("yyyy-MM-dd") + "' AND EndDate >= '" + dtEnd.ToString("yyyy-MM-dd") + "')");
        }
        return Wicresoft.Common.DataAccess.Select(typeof(Wicresoft.JDPostBoard.Entity.VehicleApply2), builder.ToString(), "StartDate,StartTime");
    }


    /// <summary>
    /// 生成车辆周使用情况列表
    /// </summary>
    /// <param name="dtCar">车辆信息</param>
    /// <param name="dtApply">车辆使用信息</param>
    /// <param name="dtTemp">周起始日</param>
    private void DrawMainTable(DataTable dtCar, DataTable dtApply, DateTime dtTemp)
    {
        #region 车辆
        this.tbVehicleApply.Controls.Clear();
        dtCar.Columns.Add("VehicleTypeCN");
        foreach (DataRow dr in dtCar.Rows)
        {
            if (dr["VehicleType"].ToString() == "0")
                dr["VehicleTypeCN"] = "公共车辆";
            else if (dr["VehicleType"].ToString() == "1")
                dr["VehicleTypeCN"] = "领导用车";
            else
                dr["VehicleTypeCN"] = "其他";
        }

        #region 表头
        TableRow HeaderTR = new TableRow();
        //for (int i = 0; i < 8; i++)
        for (int i = 0; i < 6; i++)
        {
            TableCell HeaderTC = new TableCell();
            if (i == 0)
            {
                HeaderTC.ColumnSpan = 1;
                HeaderTC.RowSpan = 2;
                HeaderTC.Width = System.Web.UI.WebControls.Unit.Percentage(15);
                int iDay = dtTemp.Day;
                int iWeek, curMonth, curYear;
                if (dtTemp.Month != dtTemp.AddDays(6).Month)
                {
                    iWeek = iDay - 7 * (int)(iDay / 7);
                    if (iWeek > 1)
                        iWeek = (int)(iDay / 7) + 2;
                    else
                        iWeek = (int)(iDay / 7) + 1;
                    this.lblWeekNum.Text = dtTemp.Year + "年" + dtTemp.Month + "月 第" + iWeek + "周";

                    if (dtTemp.Month != 12)
                    {
                        curMonth = dtTemp.Month + 1;
                        this.lblWeekNum.Text += "(" + dtTemp.Year + "年" + curMonth + "月 第1周)";
                    }
                    else
                    {
                        curYear = dtTemp.Year + 1;
                        this.lblWeekNum.Text += "(" + curYear + "年1月 第1周)";
                    }
                }
                else
                {
                    iWeek = iDay - 7 * (int)(iDay / 7);
                    if (iWeek > 1)
                        iWeek = (int)(iDay / 7) + 2;
                    else
                        iWeek = (int)(iDay / 7) + 1;
                    this.lblWeekNum.Text = dtTemp.Year + "年" + dtTemp.Month + "月 第" + iWeek + "周";
                }
            }
            else
            {
                //HeaderTC.ColumnSpan = WebCommon.CoverCount;
                HeaderTC.Text = ConvertNumToWeek(i);
                HeaderTC.CssClass = "TableHeader";
            }
            HeaderTR.Cells.Add(HeaderTC);
        }
        this.tbVehicleApply.Rows.Add(HeaderTR);
        #endregion

        HeaderTR = new TableRow();
        //for (int i = 0; i < 7; i++)
        for (int i = 0; i < 5; i++)
        {
            TableCell HeaderTC = new TableCell();
            DateTime dtCurDate = dtTemp.AddDays(i).Date;
            //HeaderTC.ColumnSpan = WebCommon.CoverCount;
            HeaderTC.Text = dtCurDate.ToString("yyyy-MM-dd");//"<a href=\"javascript:OpenWin('RoomApplyInfo_Day.aspx?Date=" + dtCurDate.ToString("yyyy-MM-dd") + "', '800', '600')\">" + dtCurDate.Month + "月" + dtCurDate.Day + "日";
            HeaderTC.BorderWidth = 1;
            HeaderTC.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
            HeaderTR.Cells.Add(HeaderTC);
        }
        this.tbVehicleApply.Rows.Add(HeaderTR);

        int CarID;
        String CarName, CarInfo;
        int iShowLen = 20;
        String temp, tempTip;

        for (int i = 0; i < dtCar.Rows.Count; i++)
        {
            TableRow TR = new TableRow();
            TR.Width = System.Web.UI.WebControls.Unit.Percentage(100);
            TableCell TC = new TableCell();
            TC.Width = System.Web.UI.WebControls.Unit.Percentage(8);
            TC.RowSpan = 1;
            TC.Height = 60;
            TC.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
            CarID = int.Parse(dtCar.Rows[i][vwVehicleApply.SQLCOL_ID].ToString());
            CarName = dtCar.Rows[i][vwVehicleApply.SQLCOL_VEHICLENAME].ToString() + "<br />" + dtCar.Rows[i][vwVehicleApply.SQLCOL_VEHICLENO].ToString();
            CarInfo = "车牌号：" + dtCar.Rows[i][vwVehicleApply.SQLCOL_VEHICLENO].ToString() + "\r\n";
            CarInfo += "车辆类型：" + dtCar.Rows[i][vwVehicleApply.SQLCOL_VEHICLETYPECN].ToString() + "\r\n";
            CarInfo += "座位数：" + dtCar.Rows[i][vwVehicleApply.SQLCOL_SEATSCOUNT].ToString();

            TC.Text = "<a href=\"JavaScript:OpenWin('VehicleInfoView.aspx?ID=" + CarID.ToString() + "', '600', '420');\">" + CarName + "</a>";
            TC.ToolTip = CarInfo;
            TC.Font.Bold = true;
            TC.CssClass = "Car";
            TC.Style.Add("cursor", "hand");
            TC.BorderWidth = 1;
            TR.Cells.Add(TC);

            //for (int j = 0; j < 7; j++)
            for (int j = 0; j < 5; j++)
            {

                dtApply.DefaultView.RowFilter = vwVehicleApply.SQLCOL_VEHICLEID + " = " + CarID.ToString() + " AND " + vwVehicleApply.SQLCOL_STARTDATE + " >= '" + dtTemp.AddDays(j).ToString("yyyy-MM-dd") + "' AND " + vwVehicleApply.SQLCOL_STARTDATE + "<'" + dtTemp.AddDays(j + 1).ToString("yyyy-MM-dd") + "'";

                if (dtApply.DefaultView.Count != 0)
                {
                    #region 上午 下午 晚上
                    TC = new TableCell();
                    TC.Wrap = true;
                    TC.BorderWidth = 1;
                    TC.BorderStyle = System.Web.UI.WebControls.BorderStyle.Solid;

                    Table tbCell = new Table();
                    tbCell.CssClass = "NoBorder";
                    tbCell.BorderWidth = 0;
                    tbCell.CellPadding = 2;
                    tbCell.CellSpacing = 0;
                    tbCell.Width = System.Web.UI.WebControls.Unit.Percentage(100);
                    tbCell.Height = System.Web.UI.WebControls.Unit.Percentage(100);
                    temp = "";
                    tempTip = "";

                    TableRow cTR;
                    TableCell cTC;
                    bool flag = true;
                    foreach (DataRowView rv in dtApply.DefaultView)
                    {
                        if (bEdit && dtTemp.AddDays(j) >= DateTime.Today && flag)
                        {
                            cTR = new TableRow();
                            cTC = new TableCell();
                            cTC.Font.Size = System.Web.UI.WebControls.FontUnit.Point(9);
                            //cTC.Height = System.Web.UI.WebControls.Unit.Percentage(100);
                            cTC.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Left;
                            cTC.VerticalAlign = System.Web.UI.WebControls.VerticalAlign.Top;
                            //cTC.Text = "<a href=\"JavaScript:OpenDialog('ShowMessage.aspx?MsgType=1&ApplyID="+ rv[vwMeetingRoomApply.SQLCOL_ID].ToString() +"','400','380');\"><img src=\"../images/icon_add.gif\" border=\"0\"></a>";
                            cTC.Text = "<a href=\"JavaScript:OpenWin('VehicleApply.aspx?StartDate=" + dtTemp.AddDays(j) + "&EndDate=" + dtTemp.AddDays(j + 1).AddMinutes(-1) + "&nc=" + new Random().Next() + "','800','600');\"><img src=\"../Images/icon_add.gif\" border=\"0\" /></a>";
                            cTR.Cells.Add(cTC);
                            tbCell.Rows.Add(cTR);
                            flag = false;
                        }

                        cTR = new TableRow();
                        cTC = new TableCell();
                        cTC.Font.Size = System.Web.UI.WebControls.FontUnit.Point(9);
                        cTC.Height = System.Web.UI.WebControls.Unit.Percentage(100 / dtApply.DefaultView.Count);
                        cTC.Style.Add("cursor", "hand");
                        cTC.VerticalAlign = VerticalAlign.Top;

                        if (rv[vwVehicleApply.SQLCOL_PURPOSE].ToString().Trim().Length > 8)
                            temp = rv[vwVehicleApply.SQLCOL_PURPOSE].ToString().Trim().Substring(0, 8) + "...";
                        else
                            temp = rv[vwVehicleApply.SQLCOL_PURPOSE].ToString().Trim();

                        tempTip = "事由：" + rv[vwVehicleApply.SQLCOL_PURPOSE].ToString() + "\r\n";
                        tempTip += "目的地：" + rv[vwVehicleApply.SQLCOL_DESTINATION].ToString() + "\r\n";
                        tempTip += "出发时间：" + DateTime.Parse(rv[vwVehicleApply.SQLCOL_STARTDATE].ToString()).ToString("yyyy-MM-dd HH:mm") + " " + rv[vwVehicleApply.SQLCOL_STARTTIME].ToString() + "\r\n";
                        tempTip += "返回时间：" + DateTime.Parse(rv[vwVehicleApply.SQLCOL_ENDDATE].ToString()).ToString("yyyy-MM-dd HH:mm") + " " + rv[vwVehicleApply.SQLCOL_ENDTIME].ToString() + "\r\n";
                        tempTip += "天数：" + rv[vwVehicleApply.SQLCOL_REMARK2].ToString() + "天\r\n";
                        tempTip += "人数：" + rv[vwVehicleApply.SQLCOL_PEOPCOUNT].ToString() + "人";


                        if (temp.Length > iShowLen)
                            temp = temp.Substring(0, iShowLen);
                        else
                            temp = temp.Trim();
                        DateTime CarStartTime = Convert.ToDateTime(rv[vwVehicleApply.SQLCOL_STARTDATE].ToString());
                        if ((this.bEdit && rv[vwVehicleApply.SQLCOL_APPLICANT].ToString().Equals(CurrentUser.Name) && rv[vwVehicleApply.SQLCOL_STATUS].ToString().Equals(VehicleUseStatus.POST)) )//|| (OrganizationHelper.IsUserInRole(CurrentUser.ID, VehicleRoles.Manage) && CarStartTime.CompareTo(DateTime.Now) > 0))
                            //	&& !dtRoom.Rows[i][vwMeetingRooms.SQLCOL_FLAG].ToString().Equals(RoomStatus.SPECIAL))
                            temp = "<a href=\"JavaScript:OpenWin('VehicleApply.aspx?opener=InfoList&Type=edit&ID=" + rv[vwVehicleApply.SQLCOL_ID].ToString() + "', '800', '600');\">" + temp + "</a>";
                        else
                            temp = "<a href=\"JavaScript:OpenWin('VehicleApplyView.aspx?Type=view&opener=Window&ID=" + rv[vwVehicleApply.SQLCOL_ID].ToString() + "', '800', '600');\">" + temp + "</a>";

                        if (!(rv["Status"].ToString().Equals(VehicleUseStatus.AUDIT) || rv["Status"].ToString().Equals(VehicleUseStatus.BALANCE)))
                        {
                            cTC.BackColor = System.Drawing.Color.FromArgb(0xff9933);
                        }
                        else
                        {
                            cTC.BackColor = System.Drawing.Color.FromArgb(0xDDDDDD);
                            cTC.Style.Add("cursor", "hand");
                        }

                        cTC.Text = temp;
                        cTC.ToolTip = tempTip;
                        cTR.Cells.Add(cTC);
                        tbCell.Rows.Add(cTR);
                        temp = "";
                    }

                    TC.Controls.Add(tbCell);
                    TR.Cells.Add(TC);
                    #endregion
                }
                else
                {

                    TC = new TableCell();

                    if (bEdit && (dtTemp.AddDays(j) > DateTime.Today || dtTemp.AddDays(j) == DateTime.Today))
                    {
                        TC.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Left;
                        TC.VerticalAlign = System.Web.UI.WebControls.VerticalAlign.Top;
                        TC.Text = "<a href=\"JavaScript:OpenWin('VehicleApply.aspx?StartDate=" + dtTemp.AddDays(j) + "&EndDate=" + dtTemp.AddDays(j + 1).AddMinutes(-1) + "&nc=" + new Random().Next() + "', '800', '600');\"><img src=\"../Images/icon_add.gif\" border=\"0\" /></a>";

                    }
                    TC.Wrap = true;
                    TC.BorderWidth = 1;
                    TC.BorderStyle = System.Web.UI.WebControls.BorderStyle.Solid;
                    TR.Cells.Add(TC);

                }
            }
            TR.BorderWidth = 1;
            this.tbVehicleApply.Rows.Add(TR);
        }

        #endregion
    }


    /// <summary>
    /// 把数字转换成星期
    /// </summary>
    /// <param name="Num">数字</param>
    /// <returns>星期</returns>
    private String ConvertNumToWeek(int Num)
    {
        switch (Num)
        {
            case 1: return "星期一";
            case 2: return "星期二";
            case 3: return "星期三";
            case 4: return "星期四";
            case 5: return "星期五";
            case 6: return "星期六";
            case 7: return "星期日";
            default: return null;
        }
    }

    /// <summary>
    /// 把星期转换成数字
    /// </summary>
    /// <param name="Week">星期</param>
    /// <returns>数字</returns>
    private int ConvertWeekToNum(String Week)
    {
        switch (Week)
        {
            case "Monday": return 0;
            case "Tuesday": return 1;
            case "Wendesday": return 2;
            case "Thursday": return 3;
            case "Friday": return 4;
            case "Saturday": return 5;
            case "Sunday": return 6;
            default: return -1;
        }
    }

    #region 注释
    //protected void btnLastWeek_Click(object sender, System.EventArgs e)
    //{
    //    DateTime Date = VehicleApplyWeekTable1.ThisDay.AddDays(-7);

    //    VehicleApplyWeekTable1.ThisDay = Date;
    //}

    //protected void btnNextWeek_Click(object sender, System.EventArgs e)
    //{
    //    DateTime Date = VehicleApplyWeekTable1.ThisDay.AddDays(7);

    //    VehicleApplyWeekTable1.ThisDay = Date;
    //}

    //protected void ddlYear_SelectedIndexChanged(object sender, System.EventArgs e)
    //{
    //    DateTime Date = new DateTime(int.Parse(this.ddlYear.SelectedItem.Text), int.Parse(this.ddlMonth.SelectedItem.Text), 1);
    //    while (!Date.DayOfWeek.ToString().Equals("Monday"))
    //        Date = Date.AddDays(-1);

    //    VehicleApplyWeekTable1.ThisDay = Date;
    //}

    //protected void btnCurWeek_Click(object sender, System.EventArgs e)
    //{
    //    DateTime dtTemp = DateTime.Today;
    //    VehicleApplyWeekTable1.ThisDay = dtTemp;
    //}
    #endregion

    protected void btnLastWeek_Click(object sender, System.EventArgs e)
    {
        DateTime Date = DateTime.Parse(this.txtDate.Text);
        Date = Date.AddDays(-7);

        InitTable(Date);
    }

    protected void btnNextWeek_Click(object sender, System.EventArgs e)
    {
        DateTime Date = DateTime.Parse(this.txtDate.Text);
        Date = Date.AddDays(7);

        InitTable(Date);
    }

    protected void ddlYear_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        DateTime Date = new DateTime(int.Parse(this.ddlYear.SelectedItem.Text), int.Parse(this.ddlMonth.SelectedItem.Text), 1);
        while (!Date.DayOfWeek.ToString().Equals("Monday"))
            Date = Date.AddDays(-1);

        InitTable(Date);
    }

    protected void btnCurWeek_Click(object sender, System.EventArgs e)
    {
        DateTime dtTemp = DateTime.Today;
        while (!dtTemp.DayOfWeek.ToString().Equals("Monday"))
            dtTemp = dtTemp.AddDays(-1);
        InitTable(dtTemp);
    }

}
